package com.sdr.sluicemapplugin.activities;

import com.bumptech.glide.Glide;
import com.ilovn.libs.fileupload.CustomMultiPartEntity;
import com.sdr.xitang.R;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class UploadZhaZhanStatus extends AppCompatActivity {

    private String userID;
    private String accessToken;
    private String SGSCD;
    private String serviceUrl = "upload/uploadStationResultData";
    private String status = "";
    private String name = "";

    private RadioGroup mRadioGroup;
    private EditText mEditText;
    private Button openWeiXin,upLoad;
    private GridView gv_photos;

    private List<String> imagePathList;
    private List<String> cacheImageList;

    //自定义的Dialog
    private Dialog mDialog;
    //显示上传进度的TextView
    private TextView tv_upload_dialog_progress;

    //权限申请返回码
    //启动相册
    private static final int OPEN_ALBUM_REQUEST_CODE = 100;
    //启动照相
    private static final int TAKE_PHOTO_REQUEST_CODE = 200;
    private ShowPhotosAdapter adapter;
    private File outputImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_zha_zhan_status);
        initIntent();
        initActionBar();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent != null){
            this.userID = intent.getStringExtra("userID");
            this.accessToken = intent.getStringExtra("accessToken");
            this.SGSCD = intent.getStringExtra("SGSCD");
            this.serviceUrl = intent.getStringExtra("serviceUrl")+serviceUrl;
            this.name = intent.getStringExtra("name");
        }
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#72D3E4")));
        actionBar.setCustomView(R.layout.baidumap_actionbar_custom);
        //设置右滑打开不可见
        actionBar.getCustomView().findViewById(R.id.iv_openRight).setVisibility(View.INVISIBLE);
        //设置标题文字
        TextView tv_titile = (TextView) actionBar.getCustomView().findViewById(R.id.tv_actionbar_title);
        tv_titile.setText(name+"巡检");
        //设置返回按钮的监听事件
        actionBar.getCustomView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {
        mRadioGroup = (RadioGroup) this.findViewById(R.id.rg_waterGateStatus);
        mEditText = (EditText) this.findViewById(R.id.edt_WaterGateDes);
        openWeiXin = (Button) this.findViewById(R.id.btn_openWeixin);
        upLoad = (Button) this.findViewById(R.id.btn_upload);
        gv_photos = (GridView) this.findViewById(R.id.gv_photos);
    }

    private void initData(){
        imagePathList = new ArrayList<String>();
        cacheImageList = new ArrayList<String>();
        adapter = new ShowPhotosAdapter(this,imagePathList);
        gv_photos.setAdapter(adapter);
    }

    private void initListener(){
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_zhazhan_normal){
                    status = "1";
                }
                if (checkedId == R.id.rb_zhazhan_breakdown){
                    status = "0";
                }
            }
        });

        openWeiXin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent();
                    ComponentName cmp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
                    intent.setAction(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setComponent(cmp);
                    startActivity(intent);
                } catch (Exception e) {
//                    e.printStackTrace();
                    Toast.makeText(UploadZhaZhanStatus.this, "您的手机没有安装微信", Toast.LENGTH_SHORT).show();
                }
            }
        });

        upLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mEditText.getText().toString();

                if (!"".equals(status)){
                    if (!"".equals(content)){
                        if (!imagePathList.isEmpty()){
                            MyTask myTask = new MyTask();
                            myTask.execute();
                        }else {
                            Toast.makeText(UploadZhaZhanStatus.this, "至少需要一张图片", Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(UploadZhaZhanStatus.this, "闸站描述不能为空", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(UploadZhaZhanStatus.this, "请选择状态", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //启动相册
    private void startSystemAlbum(){

        boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        Intent intent = null;

        if (isKitKat){
            intent = new Intent(Intent.ACTION_PICK);
        }else {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
        }
        intent.setType("image/*");
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, OPEN_ALBUM_REQUEST_CODE);
    }
    //启动系统相机
    private void startSystemCamera(){
        //拍照图片的名字
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        Date date = new Date(System.currentTimeMillis());
        String fileName = format.format(date);
        //创建File对象用于存储拍照的图片 SD卡根目录
        //File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);
        //存储至DCIM文件夹
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        outputImage = new File(path,fileName+".jpg");
        try {
            if(outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch(IOException e) {
            e.printStackTrace();
        }
        //将File对象转换为Uri并启动照相程序
        Uri imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //照相
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //指定图片输出地址
        startActivityForResult(intent,TAKE_PHOTO_REQUEST_CODE); //启动照相
        //拍完照startActivityForResult() 结果返回onActivityResult()函数
    }

    //图片缓存
    private void createImageCache(File outputImage) {
        //拍照图片的名字
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        Date date = new Date(System.currentTimeMillis());
        String fileName = format.format(date);
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"cache";
        File path = new File(filePath);
        if (!path.exists()){
            path.mkdir();
        }
        File cacheFile = new File(filePath+File.separator+"Cache_"+fileName+".jpeg");
        try {
            if(cacheFile.exists()) {
                cacheFile.delete();
            }
            cacheFile.createNewFile();
        } catch(IOException e) {
            e.printStackTrace();
        }
        //开始进行压缩图片
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        Bitmap bitmapBefor = BitmapFactory.decodeFile(outputImage.getAbsolutePath(),options);
        //获取原图片的宽高
        int widthBig = options.outWidth;
        int heightBig = options.outHeight;
        //获取屏幕的宽高
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthSmall = metrics.widthPixels;
        int heightSmall = metrics.heightPixels;

        int widthScale = widthBig/widthSmall;
        int heightScale = heightBig/heightSmall;

        int scale = 1;
        if (widthScale>=heightScale && widthScale>=1){
            scale = widthScale;
        }else if (widthScale<heightScale && heightScale>=1){
            scale = heightScale;
        }
        options.inSampleSize=scale;
        options.inJustDecodeBounds=false;
        Bitmap bitmapLater = BitmapFactory.decodeFile(outputImage.getAbsolutePath(),options);

        //将bitmap转化为File文件
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
            bitmapLater.compress(Bitmap.CompressFormat.JPEG, 60, bos);

            //将缓存路径添加到集合中
            cacheImageList.add(cacheFile.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!cacheImageList.isEmpty()){
            for (int i = 0; i < cacheImageList.size(); i++) {
                new File(cacheImageList.get(i)).delete();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == OPEN_ALBUM_REQUEST_CODE){
            startSystemAlbum();
        }
        if (requestCode == TAKE_PHOTO_REQUEST_CODE){
            startSystemCamera();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null){
            if (requestCode == OPEN_ALBUM_REQUEST_CODE){
                try {
                    Uri uri = data.getData();
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
                    if(cursor.moveToFirst()) {
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        String path = cursor.getString(column_index);
                        imagePathList.add(path);
                        adapter.notifyDataSetChanged();
                        createImageCache(new File(path));
                    }
                    cursor.close();
                } catch (Exception e) {
                    Log.e("TAG-->Error", e.toString());
                }
            }
        }
        if (requestCode == TAKE_PHOTO_REQUEST_CODE){
            if (outputImage.length()>0){
                String imagePath = outputImage.getAbsolutePath();
                imagePathList.add(imagePath);
                adapter.notifyDataSetChanged();
                //创建缓存
                createImageCache(outputImage);
            }else {
                outputImage.delete();
            }
        }
    }

    private class ShowPhotosAdapter extends BaseAdapter{

        private Activity activity;
        private List<String> imagePathList;

        public ShowPhotosAdapter(Activity activity, List<String> imagePathList) {
            this.activity = activity;
            this.imagePathList = imagePathList;
        }

        @Override
        public int getCount() {
            return imagePathList.size()+1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(activity, R.layout.item_gridview_takephotos, null);
            ImageView iv_photo = (ImageView) convertView.findViewById(R.id.iv_photo);
            ImageView iv_delete = (ImageView) convertView.findViewById(R.id.iv_delete);
            if (position == imagePathList.size()){
                iv_photo.setBackgroundResource(R.drawable.btn_add_images);
                iv_delete.setVisibility(View.INVISIBLE);
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //显示PopWindow
                        showPopwindow();
                    }
                });
            }else if (!imagePathList.isEmpty()){
                Glide.with(activity).load(imagePathList.get(position)).into(iv_photo);
                //删除图标的点击事件
                iv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                            //将图片删除
//                            new File(imagePathList.get(position)).delete();
                        //删除缓存图片
                        new File(cacheImageList.get(position)).delete();
                        imagePathList.remove(position);
                        cacheImageList.remove(position);
                        notifyDataSetChanged();
                    }
                });
            }

            return convertView;
        }


        private void showPopwindow(){
            View view = View.inflate(activity,R.layout.popwindow_takephoto_album,null);

            final PopupWindow window = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
            window.setFocusable(true);
            setTransformBg(0.5f);
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(Color.parseColor("#00000000"));
            window.setBackgroundDrawable(dw);
            // 设置popWindow的显示和消失动画
            window.setAnimationStyle(R.style.ShowPopwindow);
            // 在底部显示
            window.showAtLocation(activity.findViewById(R.id.ll_upLoadZhaZhanStatus),
                    Gravity.BOTTOM, 0, 0);
            //点击事件
            view.findViewById(R.id.tv_popwindow_album).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //6.0申请权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, OPEN_ALBUM_REQUEST_CODE);
                    }else {
                        startSystemAlbum();
                    }
                    window.dismiss();
                }
            });

            view.findViewById(R.id.tv_popwindow_takephoto).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //6.0申请权限
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},TAKE_PHOTO_REQUEST_CODE);
                    }else {
                        startSystemCamera();
                    }
                    window.dismiss();
                }
            });

            view.findViewById(R.id.tv_popwindow_cancle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    window.dismiss();
                }
            });

            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    setTransformBg(1.0f);
                }
            });
        }

        private void setTransformBg(float alpha){
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = alpha;
            getWindow().setAttributes(lp);
        }
    }

    private class MyTask extends AsyncTask<String,Integer,String>{


        private long totalSize;

        @Override
        protected String doInBackground(String... params) {
            HttpPost httpPost = new HttpPost(serviceUrl);
            HttpClient httpClient = new DefaultHttpClient();
            //设置请求超时时间
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
            try {
                CustomMultiPartEntity multiPartEntity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                        Charset.forName("utf-8"), new CustomMultiPartEntity.ProgressListener() {
                    @Override
                    public void transferred(long l) {
                        publishProgress((int) ((l / (float) totalSize) * 100));
                    }
                });
                multiPartEntity.addPart("userId",new StringBody(userID));
                multiPartEntity.addPart("accessToken",new StringBody(accessToken));
                multiPartEntity.addPart("status",new StringBody(status));
                multiPartEntity.addPart("SGSCD",new StringBody(SGSCD));
                multiPartEntity.addPart("sm",new StringBody(mEditText.getText().toString(), Charset.forName("utf-8")));
                for (int i = 0; i < cacheImageList.size(); i++) {
                    multiPartEntity.addPart("file",new FileBody(new File(cacheImageList.get(i))));
                }
                totalSize =  multiPartEntity.getContentLength();
                httpPost.setEntity(multiPartEntity);
                HttpResponse response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                    InputStream is= response.getEntity().getContent();
                    byte [] b =new byte[1024];
                    int len = 0;
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    while((len=is.read(b))!=-1){
                        bos.write(b,0,len);
                    }
                    is.close();
                    bos.close();
                    String result = new String(bos.toByteArray());
                    JSONObject jsonObject = new JSONObject(result);
                    int statusCode = jsonObject.getInt("code");
                    if (statusCode==200){
                        return "上传成功";
                    }else {
                        return "上传失败";
                    }
                }else {
                    return "网络异常";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }

        //更新进度
        @Override
        protected void onProgressUpdate(Integer... values) {
            if (tv_upload_dialog_progress != null) {
                tv_upload_dialog_progress.setText("正在上传(" + values[0] + "%)");
            }
        }

        //当任务执行之前开始调用此方法，可以在这里显示进度对话框
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showCustomerDialog();
        }

        //执行完毕
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //让dialog消失
//            if (mDialog.isShowing()){
//                mDialog.dismiss();
//            }
            if(mDialog.isShowing()){
                mDialog.dismiss();
            }
            Toast.makeText(UploadZhaZhanStatus.this, s, Toast.LENGTH_LONG).show();
            Log.e("返回结果", s);
            if (s.startsWith("上传成功")){
                //消除所有状态
                mRadioGroup.clearCheck();
                mEditText.setText("");
                imagePathList.clear();
                for (int i = 0; i < cacheImageList.size(); i++) {
                    new File(cacheImageList.get(i)).delete();
                    if (i == cacheImageList.size()-1){
                        cacheImageList.clear();
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void showCustomerDialog() {
        //显示自定义的dialog
        mDialog = new Dialog(UploadZhaZhanStatus.this,R.style.GatelistDialog);
        View dialog_upload = View.inflate(this,getApplication().getResources()
                .getIdentifier("customer_dialog","layout",getApplication().getPackageName()),null);
        //设置动画
        ImageView iv_dialogLoading = (ImageView)dialog_upload.findViewById(getApplication().getResources()
                .getIdentifier("iv_dialogLoading","id",getApplication().getPackageName()));

        tv_upload_dialog_progress = (TextView) dialog_upload.findViewById(R.id.tv_upload_dialog_progress);
        Animation animation = AnimationUtils.loadAnimation(this,getApplication().getResources()
                .getIdentifier("anim_rotate","anim",getApplication().getPackageName()));
        LinearInterpolator lin = new LinearInterpolator();
        animation.setInterpolator(lin);
        iv_dialogLoading.setAnimation(animation);
        //得到屏幕的宽
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        mDialog.setContentView(dialog_upload,new LinearLayout.LayoutParams(width/3,width/3));
        mDialog.setCancelable(false);
        if (!mDialog.isShowing()){
            mDialog.show();
        }
    }
}
